package com.zxy.springboot_goods.controller;


import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.itextpdf.text.Document;
import com.itextpdf.text.DocumentException;
import com.itextpdf.text.pdf.PdfPTable;
import com.itextpdf.text.pdf.PdfWriter;
import com.zxy.springboot_goods.config.AjaxResult;
import com.zxy.springboot_goods.config.PDFUtils;
import com.zxy.springboot_goods.entity.Goods;
import com.zxy.springboot_goods.entity.Product;
import com.zxy.springboot_goods.service.IGoodsService;
import com.zxy.springboot_goods.service.IProductService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.kafka.config.ConcurrentKafkaListenerContainerFactory;
import org.springframework.kafka.core.ConsumerFactory;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.kafka.listener.ContainerProperties;
import org.springframework.kafka.support.SendResult;
import org.springframework.util.concurrent.ListenableFuture;
import org.springframework.util.concurrent.ListenableFutureCallback;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;

import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletResponse;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author lenovo
 * @since 2021-11-01
 */
@RestController
@RequestMapping("/goods")
public class GoodsController {

    @Autowired
    private IGoodsService goodsService;
    @Autowired
    private IProductService productService;
    @Autowired
    private KafkaTemplate kafkaTemplate;
    @Autowired
    private RedisTemplate redisTemplate;

    /*查询列表*/
    @RequestMapping("getGoods")
    public AjaxResult getGoods(Goods goods, @RequestParam(defaultValue = "1") Integer pageNum, @RequestParam(defaultValue = "3")Integer pageSize){
        PageHelper.startPage(pageNum,pageSize);
        List<Goods> list = goodsService.getGoods(goods);
        PageInfo<Goods> info = new PageInfo<>(list);

        //如何解决消息重复消费问题?
        //发消息的时候 kafkaTemplate.send("1904a", "mail-msg", "msg");中间的参数是一个文艺的key标识


        //kafka发送
        //发送消息,生产者的消息确认机制
        ListenableFuture<SendResult<String,String>> send = kafkaTemplate.send("look",
                "send", JSONObject.toJSONString(list)+"send");

        redisTemplate.opsForValue().set("send",JSONObject.toJSONString(list));//往reids中存入唯一标识


        //kafka发送机制
        send.addCallback(new ListenableFutureCallback<SendResult<String, String>>() {
            @Override
            public void onFailure(Throwable ex) {
                System.out.println("消息发送失败会在这里执行");
                //再次发送,直到消费方确认
            }

            @Override
            public void onSuccess(SendResult<String, String> result) {
                System.out.println("消息发送成功");
            }
        });
        return AjaxResult.ok(info);
    }

    /*添加数据*/
    @RequestMapping("addGoods")
    public AjaxResult addGoods(@RequestBody Goods goods){
        System.err.println(goods);
        boolean b = goodsService.saveOrUpdate(goods);
        return AjaxResult.ok();
    }

    /*通过id查询数据*/
    @RequestMapping("getById")
    public AjaxResult getById(Goods goods){

        Goods good = goodsService.getById(goods.getId());
        Product product = productService.getById(good.getProductId());
        good.setAddress(product.getAddress());
        good.setProductName(product.getProductName());
        return AjaxResult.ok(good);
    }

    /*删除的方法*/
    @RequestMapping("toDelete")
    public AjaxResult toDelete(@RequestBody Goods goods){
        boolean b = goodsService.removeById(goods.getId());

        return AjaxResult.ok(b);
    }

    @RequestMapping("orderToJSON")
    public AjaxResult orderToJSON(@RequestBody Goods goods) throws DocumentException, IOException, NoSuchFieldException, IllegalAccessException {
        ArrayList<Object> list = new ArrayList<>();
        list.add(goods);

        Document document = new Document();
        PdfWriter doc = PDFUtils.createDoc(document, "D:/picture/" + goods.getId() + ".pdf");

        PdfPTable pdfPTable = PDFUtils.addTable(doc, new String[]{"药品名称", "价格", "生产日期", "产品批号", "供应商"},
                new String[]{"goodsName", "price", "goodsDate", "piHao", "productName"},
                list, 50, 500);
        document.add(pdfPTable);
        document.close();
        return AjaxResult.ok();

    }

    //预览
    @RequestMapping("toLookBook")
    public void toLookBook(HttpServletResponse response,Integer id) throws Exception {
        PDFUtils.YuLan(response,"D:/picture/"+id+".pdf");
    }

    //下载pdf
    @RequestMapping("downLoadPdf")
    public void downLoadPdf(Goods goods,HttpServletResponse response) throws IOException {
        PDFUtils.download(response,"D:/picture/"+goods.getId()+".pdf","D:/picture/111.pdf",0);
    }

    //电子签章
    @RequestMapping("Signature")
    public AjaxResult Signature(@RequestBody Goods goods) throws IOException, DocumentException {
        PDFUtils.markImage("D:/picture/"+"tu.jpg",
                new FileInputStream("D:/picture/"+goods.getId()+".pdf"),
                new FileOutputStream("D:/picture/"+goods.getId()+"xiao.pdf"),"周小勇");
        return AjaxResult.ok();
    }


}
